package com.ca.ridersclubapplication.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.AccountActivity;
import com.ca.ridersclubapplication.PaperActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.CommentDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.TimeUtils;
import com.ca.ridersclubapplication.view.button.IconButton;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentHolder> {

    private final Activity activity;
    private List<CommentDto> list = new ArrayList<>();

    public CommentAdapter(Activity activity, List<CommentDto> list) {
        this.activity = activity;
        this.list = list == null ? new ArrayList<>() : list;
    }

    @NonNull
    @Override
    public CommentHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item_layout, parent, false);
        return new CommentHolder(view);
    }

    @SuppressLint({"UseCompatLoadingForDrawables", "InflateParams"})
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull CommentHolder holder, int position) {

        CommentDto dto = list.get(position);
        if (dto == null) {
            return;
        }
        ImageUtils.loadCircleImage(activity, FileRequester.HEADER_BY_ID_BASE_URL + dto.getAccountId(), holder.headerView);
        holder.nameView.setText(dto.getAccountName());
        holder.contentView.setText(dto.getContent());
        holder.timeView.setText(TimeUtils.parseShowDateTime(dto.getTime()));
        holder.supportButton.setValue(dto.getSupportCount());
        holder.supportButton.setActiveIcon(activity.getResources().getDrawable(R.drawable.ic_support));

        Long accountId = DataHandler.getToken(activity).getId();
        if (accountId.equals(dto.getAccountId())) {
            holder.meView.setVisibility(View.VISIBLE);
        }
        else {
            holder.meView.setVisibility(View.GONE);
        }

        //  请求是否点赞
        if (DataHandler.isLogin(activity)) {
            PaperRequester.isSupportComment(activity, dto.getId(), new AfterExecutor<Boolean>() {
                @Override
                public void execute(Result<Boolean> result) {
                    Boolean isSupport = result.getData();
                    //  已经点赞
                    holder.supportButton.setActive(result.isSuccess() && isSupport != null && isSupport);
                    holder.supportButton.setOnClickListener(v -> {

                        if (!holder.supportButton.isActive()) {

                            PaperRequester.supportComment(activity, dto.getId(), new AfterExecutor<String>() {
                                @Override
                                public void execute(Result<String> result) {
                                    if (result.isSuccess()) {
                                        holder.supportButton.setActive(true);
                                        holder.supportButton.setValue(holder.supportButton.getValue() + 1);
                                    }
                                }
                            });
                        }
                        else {

                            PaperRequester.deleteSupportComment(activity, dto.getId(), new AfterExecutor<String>() {
                                @Override
                                public void execute(Result<String> result) {
                                    if (result.isSuccess()) {
                                        holder.supportButton.setActive(false);
                                        holder.supportButton.setValue(holder.supportButton.getValue() - 1);
                                    }
                                }
                            });
                        }
                    });
                }
            });
        }
        else {
            holder.supportButton.setActive(false);
        }

        holder.parentCL.setOnClickListener(v -> {});

        if (dto.getAccountId().equals(DataHandler.getToken(activity).getId())) {
            holder.parentCL.setOnClickListener(v -> {
                Dialog dialog = new Dialog(activity);
                View dialogView = LayoutInflater.from(activity).inflate(R.layout.delete_comment_dialog_layout, null);
                dialog.setContentView(dialogView);
                TextView cancelButton = dialogView.findViewById(R.id.btn_cancel);
                TextView sureButton = dialogView.findViewById(R.id.btn_sure);
                cancelButton.setOnClickListener(bv -> {
                    dialog.dismiss();
                });
                sureButton.setOnClickListener(bv -> {
                    PaperRequester.deleteComment(activity, dto.getId(), new AfterExecutor<String>() {
                        @SuppressLint("NotifyDataSetChanged")
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                //  删除成功
                                list.remove(dto);
                                notifyDataSetChanged();
                                PaperActivity a = (PaperActivity) CommentAdapter.this.activity;
                                a.descCommentCount();
                            }
                            else {
                                Toast.makeText(activity, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            dialog.dismiss();
                        }
                    });
                });
                dialog.show();
            });
        }

        holder.headerView.setOnClickListener(v -> {
            Intent intent = new Intent(activity, AccountActivity.class);
            intent.putExtra("accountId", dto.getAccountId());
            activity.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("NotifyDataSetChanged")
    public void setList(List<CommentDto> list) {
        if (list == null) {
            list = new ArrayList<>();
        }

        if (this.list.equals(list)) {
            return;
        }

        this.list = list;
        notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void appendList(List<CommentDto> list) {
        if (list == null) {
            return;
        }
        this.list.addAll(list);
        notifyDataSetChanged();
    }

    public void addItem(CommentDto dto) {
        this.list.add(0, dto);
        notifyItemInserted(0);
    }

    public List<CommentDto> getList() {
        return list;
    }

    public static class CommentHolder extends RecyclerView.ViewHolder {

        public ConstraintLayout parentCL;
        public ImageView headerView;
        public TextView nameView;
        public TextView meView;
        public TextView contentView;
        public TextView timeView;

        public IconButton supportButton;

        public CommentHolder(@NonNull View view) {
            super(view);

            parentCL = view.findViewById(R.id.cl_parent);
            headerView = view.findViewById(R.id.iv_header);
            nameView = view.findViewById(R.id.tv_name);
            meView = view.findViewById(R.id.tv_me);
            contentView = view.findViewById(R.id.tv_content);
            timeView = view.findViewById(R.id.tv_time);

            supportButton = view.findViewById(R.id.ib_support);
        }
    }
}
